package com.shishuo.cms.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.shishuo.cms.dao.MenuDao;
import com.shishuo.cms.dao.UserMenuDao;
import com.shishuo.cms.entity.MenuEntity;
import com.shishuo.cms.entity.RoleEntity;
import com.shishuo.cms.entity.UserMenuEntity;
import com.shishuo.cms.entity.vo.PageVo;
@Service
public class UserMenuService extends BaseService<UserMenuEntity, Integer> implements InitializingBean {

	
	private UserMenuDao userMenuDao;
	private static Map<String, UserMenuEntity> allMenuMap=new HashMap<String, UserMenuEntity>();
	
	@Autowired
	public void setUserMenuDao(UserMenuDao userMenuDao) {
		super.setBaseDao(userMenuDao);
		this.userMenuDao=userMenuDao;
	}

	public List<UserMenuEntity> getMenus(int id) {
		return userMenuDao.getMenus(id);
	}

	public List<UserMenuEntity> getMenus(int id, int userId) {
		return userMenuDao.getMenus(id, userId);
	}

	public List<UserMenuEntity> getMenus() {
		return userMenuDao.getMenus();
	}

	public List<UserMenuEntity> getChildMenus(int parentId) {
		return userMenuDao.getChildMenus(parentId);
	}

	/**
	 *
	 * @param pageNum
	 * @return
	 * @throws Exception 
	 */
	public Object getAllListPage(int pageNum) throws Exception
	{
		PageVo<UserMenuEntity> pageVo = new PageVo<UserMenuEntity>(pageNum);
		List<UserMenuEntity> list = this.getAllList(pageVo.getOffset(), pageVo.getRows());
		pageVo.setList(list);
		pageVo.setCount(this.getAllListCount());
		return pageVo;
	}

	/**
	 * 判断当前url是否在数据库中存在
	 * @return
	 */
	public boolean isExist(String requestURI)
	{
		return allMenuMap.containsKey(requestURI);
	}

	/* 
	 * 初始化完毕之后执行此方法
	 */
	public void afterPropertiesSet() throws Exception
	{
		List<UserMenuEntity> allEntities=userMenuDao.getMenus();
		if (null!=allEntities)
		{
			for (int i = 0; i < allEntities.size(); i++)
			{
				allMenuMap.put(allEntities.get(i).getMenuUrl(), allEntities.get(i));
			}
		}
		
	}

	/**
	 * 保存url到菜单中，并加载到内存中
	 * @param entity
	 * @throws Exception 
	 */
	public void save(UserMenuEntity entity) throws Exception
	{
		allMenuMap.put(entity.getMenuUrl(), entity);
		this.insert(entity);
	}
}
